#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include <gtk/gtk.h>


#define DEBUG printf
#define DEFAULT_INTERFACE  "eth1"
#define FLAG_MAX 6

char conf_flag[FLAG_MAX][32]={ "KMGMT", "ESSID", "MODE", "KEY", "Encryption" , "KINDEX" };
char com_flag[FLAG_MAX][32]={ "key_mgmt" ,"essid" ,"mode", "key", "enc", "" };

char * readfile(const char * file_path)
{
	int fd,file_lenght=0,ret;
	char *data=NULL;	
	if(!file_path)
		goto err;
	fd=open(file_path, O_RDONLY);
	if(fd==-1)
		goto err;
	file_lenght=lseek(fd,0,SEEK_END);
	lseek(fd,0,SEEK_SET);
	if(file_lenght<=0)
		goto err;
	data=(char * )malloc(file_lenght+1);
	if(data==NULL)
		goto err;
	ret=read(fd,data,file_lenght);
	if(ret<=0)
		goto err;
	close(fd);
	return data;	
err:
	if(data)
		free(data);
	if(fd==0)
		close(fd);
	return NULL;
}

int check_access(char *interface,int times)
{
    char cmd[128];
    int j,ret;
    sprintf(cmd, "/sbin/iwcheck-access %s", interface);
    for(j=0;j<times;j++) {
        ret=system(cmd);
        //DEBUG("ret=%d\r\n",ret);
        if(ret!=0)
            return 0;
        //DEBUG("sleep 5\r\n");
        sleep(2);
        
    }
    return -1;
}


int wifi_run_data(char *data,char *interface,char **cell_id,int cell_count)
{
	int i,j,k,ret;
	if(!data)
		return -1;
	char *start=data,*end=data;
	char *search[FLAG_MAX];
	char tmp_buf[128],com_buf[512];
        char essid_buf[128];
        char kindex_buf[128];
        char key_buf[128];
        char system_buf[128];
        char *tmp ;
        char *p,*q;
        
        
	DEBUG("~~~start~~~~\r\n");
        
	if(!data||!interface||!cell_id||cell_count==0)
		return;		
	do
	{
		//sprintf(com_buf,"/sbin/iwset %s ",interface);
		start=end;
		if(start==NULL)
			break;
		end=strstr(end+strlen("USERCELL"),"USERCELL");
                //shuai
               search[0]=strstr(start,conf_flag[0]);
		
                if(!search[0])
			break;
                	
		if(end)
			if(end<search[0])
				break;	
                        	
		sscanf(search[0],"%*s%s",tmp_buf);
                if(atoi(tmp_buf))
                {
                   sprintf(com_buf,"/sbin/iwset wpa %s ",interface);
                }
                else
                    sprintf(com_buf,"/sbin/iwset %s ",interface);
                //
                    for(i=1;i<FLAG_MAX;i++)
                    {
			search[i]=strstr(start,conf_flag[i]);
			if(!search[i])
				break;
			if(end)
                            if(end<search[i])
				break;	                        
			
			if(strcmp(conf_flag[i],"ESSID")==0)
			{
                            p = strstr(search[i],"\r\n");
                            if(!p)
                                p = strchr(search[i],'\n');   
                            q = search[i]+strlen("ESSID ");
                            strncpy(tmp_buf,q,p-q);
                            tmp_buf[p-q]=0;
				for(k=0;k<cell_count;k++)
                                {
                                    if(cell_id[k]==NULL)
					continue;
					if(strcmp(tmp_buf,cell_id[k])==0)
					break;
				}
                                
				if(k>=cell_count)
				{
                                     DEBUG("this essid %s no fount \r\n",tmp_buf);
				     break;
				}
                                
                                
                                sprintf(system_buf, "echo \"%s\" >/tmp/essid_tmp", tmp_buf);
                                system(system_buf);
                                
                                sprintf(essid_buf, "\"%s\"",tmp_buf);
                                strcpy(tmp_buf,essid_buf);
                                
			}
                        else if (strcmp(conf_flag[i], "KEY") == 0 )
                        {
                                p = strstr(search[i],"\r\n");
                                if(!p)
                                    p = strchr(search[i],'\n');   
                                q = search[i]+strlen("KEY ");
                                strncpy(tmp_buf,q,p-q);
                                tmp_buf[p-q]=0;
                            
                                sprintf(system_buf, "echo \"%s\" >/tmp/key_tmp", tmp_buf);
                                system(system_buf);
                                
                                sprintf(key_buf, "\"%s\"",tmp_buf);
                                strcpy(tmp_buf,key_buf);
                            
                        }
                        else if (strcmp(conf_flag[i], "KINDEX") == 0)
                        {
                            ret=sscanf(search[i],"%*s%s",tmp_buf);
                            
                            if(atoi(tmp_buf) != 0)
                                sprintf(kindex_buf, "[%s]",tmp_buf);
                            else
                                strcpy(kindex_buf,g_strdup_printf("[1]"));
                            
                            strcpy(tmp_buf,kindex_buf);
                            
                        }
                        else
                            ret=sscanf(search[i],"%*s%s",tmp_buf); //get last string
			if(ret==-1)
				break;
			sprintf(com_buf,"%s %s %s",com_buf,com_flag[i],tmp_buf);
                        
                    }
                
		if(i<FLAG_MAX)
			continue;
		DEBUG("com_buf:\r\n%s\r\n",com_buf);
                system(com_buf);
		//sprintf(com_buf,"/sbin/iwcheck-access %s",interface);
                //check_access;
                if(check_access(interface,10)==0)
                        return 0;

	}while(1);
	/*
        for(i=0;i<;i++)//link no key wireless
        {
            check_access
        }*/
        
	return -1;
}

static int getcell_essid(char **cell_id,char *interface)
{
	FILE *pipe;    
	char com_buf[256];
	char buffer[256];
	char *start,*end;
	int ret=0;
	
	sprintf(com_buf,"iwset %s key off",interface);
	system(com_buf);
	sprintf(com_buf,"iwlist %s scan",interface);
	pipe = popen (com_buf, "r");
	if(!pipe)
	{
		DEBUG("pipe error!!!");
		return -1;
	}
	while ((feof(pipe) == 0)){
             if(ret>=128)
             	break;
             fgets (buffer, 256, pipe); 
             //printf("~~~~buffer=%s\r\n",buffer);
             if(start=strstr(buffer,"ESSID:\""))
             {
             	start=start+strlen("ESSID:\"");
             	end=strchr(start,'\"');
             	if(end)
             	{
             		*end=0;
             		printf("get cell=%s\r\n",start);
             		cell_id[ret++]=strdup(start);	
             	}
             }
    }
	pclose(pipe);
    return ret;
}
static char *get_data(const char *data,const char *target)
{
	char *ret,tmp_buf[256]={0};
	if(!data||!target)
		return;
	ret=strstr(data,target);
	if(ret)
	{
		sscanf(ret,"%*s%s\n%*s",tmp_buf);
		return strdup(tmp_buf);

	}
	printf("not fount data[%s]\r\n",target);
	return strdup("");
	
}

static int check_adhoc(const char *interface)
{
	if(!interface)
		return 0;
	char *data=readfile("/etc/wireless.conf");
	char *wifigroup;
	if(data)
	{
		wifigroup=get_data(data,"wifigroup");
		if(atoi(wifigroup))
		{
			char *essid,*key,*enc,cmd[256];
			essid=get_data(data,"ESSID");
			key=get_data(data,"KEY");
			enc=get_data(data,"Encryption");
			sprintf(cmd,"/sbin/iwset \"%s\" essid \"%s\" mode 1 key \"%s\" enc \"%s\"",interface,essid,key,enc);
			system(cmd);
			printf("wifigroup:%s\n",cmd);
			free(essid);
			free(key);	
			free(enc);		
			free(wifigroup);
			free(data);
			
			return 1;
		}
		free(wifigroup);
		free(data);
		return 0;
	}
	return 0;
}

static void show_help()
{
	printf("wifi-chec\r\n");
	printf("		[--interface interface]		default interface=%s\r\n",DEFAULT_INTERFACE);
	printf("		[--conf-file conf-file]		wifi configure file(need!)\r\n");
	printf("		[--help]									show help\r\n");
}

int main(int argc, char **argv) 
{
	int i,ret,cell_count;
	char *path=NULL,*data=NULL,*interface=NULL,com_buf[64],*cell_id[128];
	printf("***iwlink-group***\r\n");
	for(i=1;i<argc;i++)
	{
		if(strcmp(argv[i],"--interface")==0)
			interface=argv[++i];
		if(strcmp(argv[i],"--conf-file")==0)
			path=argv[++i];
		if(strcmp(argv[i],"--help")==0)
		{
			show_help();
			return -1;	
		}	
	}
	if(path==NULL)
	{
		show_help();
		return -1;
	}
	if(interface==NULL)
		interface=DEFAULT_INTERFACE;	
		
	if(check_adhoc(interface))
		return 0;
	
	
	/*sprintf(com_buf,"iwcheck-access %s",interface);
	ret=system(com_buf);
	//DEBUG("ret=%d\r\n",ret);
	if(ret!=0)
		return 0;	*/
		
	cell_count=getcell_essid(cell_id,interface);
        printf("cell_count = %d \n", cell_count);
	if(cell_count<=0)
        {    
            DEBUG("cell_count <=0 (%d)\r\n",cell_count);
		return -1;
        }
	/*if(cell_count>0)
	{
		for(i=0;i<cell_count;i++)
			DEBUG("cell_id[%d]=%s",i,cell_id[i]);
		return -1;
	}	
	*/
	data=readfile(path);
	
	return wifi_run_data(data,interface,cell_id,cell_count);
	
	//return get_addvanced_setting_from_file (path);	
}
